package com.ficus.road.maintain.third.zh;

import com.fasterxml.jackson.databind.JsonNode;
import com.ficus.road.maintain.config.DiseaseConfig;
import com.ficus.road.maintain.config.DiseaseConfigInfo;
import com.ficus.road.maintain.core.model.*;
import com.ficus.road.maintain.core.utils.JsonUtils;
import com.ficus.road.maintain.dao.HitDao;
import com.ficus.road.maintain.dao.RoadInfoDao;
import com.ficus.road.maintain.util.MyDateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.ficus.road.maintain.core.model.HitStatusEnum.*;

@Service
@Slf4j
public class RestoreHitService {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    DiseaseConfig diseaseConfig;
    @Autowired
    RoadInfoDao roadInfoDao;
    @Autowired
    HitDao hitDao;

//        @PostConstruct
    private void syncHit() {
        MultiValueMap<String, String> header = new HttpHeaders();
        String token = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyaWQiOiJZSVRVVEVDSCIsImxvZ2luX3VzZXJfa2V5IjoiMmE2MjYzZTgtYTBkZC00NmJjLTliZWUtYWRkZWJkOTJhMDZkIn0.Od0yxkjxIY_l0ncr07iKjb8EB26_sOaiJH36LdQLIMAirBgj9pn8LBONMF8UNNXhFhYISAijQDW1LpwPSTvpFA";

        header.set("Authorization", token);
        Map<String, Object> pararm = Maps.newHashMap();
        pararm.put("pageNum", 1);
        pararm.put("pageSize", 10000);
        pararm.put("stime", Lists.newArrayList("2021-01-01", "2022-12-21"));
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<Map<String, Object>>(pararm, header);
        ResponseEntity<JsonNode> exchange = restTemplate.exchange("https://117.131.26.43:9999/prod-api/system/complainunfinishedhisdata/diseaseretrieval",
                HttpMethod.PUT, httpEntity, JsonNode.class);
        JsonNode rows = exchange.getBody().get("rows");
        Map<String, HitStatusEnum> curstatusMap = Maps.newHashMap();
        //"未派单"
        curstatusMap.put("1", UNDISPATCH);
        //"派单中"
        curstatusMap.put("2", DISPATCHED);
        //"处理中"
        curstatusMap.put("3", PROCESSING);
        //"退单待批复"
        curstatusMap.put("4", REJECTED);
        //"结案待批复"
        curstatusMap.put("5", COMPLETE);
        //"完结待批复"
        curstatusMap.put("6", CONFIRMED);

        Map<String, RoadInfo> roadNameMap = roadInfoDao.findAll().stream().collect(Collectors.toMap(RoadInfo::getRoadName, v -> v, (k1, k2) -> k1));

        Map<String, String> typeMap = Maps.newHashMap();
        //"路面沉陷"
        typeMap.put("1", "PIC_POTHOLES_RESULT_SETTLEMENT");
        //标线淡化
        typeMap.put("4", "PIC_TRAFFIC_LINE_DISEASE_RESULT_DISEASE_OCCLUSION");
        //标志遮挡
        typeMap.put("6", "PIC_TRAFFIC_SIGN_DISEASE_RESULT_DISEASE_OCCLUSION");
        //道路作业
        typeMap.put("9", "PIC_WORKING_DISEASE_RESULT_DISEASE_ROAD_DOCUMENTED");
        //护栏倒伏
        typeMap.put("12", "PIC_FENCE_DISEASE_RESULT_DISEASE_FALL_DOWN");
        //车辙
        typeMap.put("15", "PIC_CRACK_RESULT_CAR_RUT");
        //路面沉陷
        typeMap.put("16", "PIC_POTHOLES_RESULT_SETTLEMENT");
        //裂缝（沥青路面）
        typeMap.put("20", "PIC_CRACK_RESULT_PIC_CRACK");
        //裂缝（沥青路面）
        typeMap.put("21", "PIC_CRACK_RESULT_PIC_CRACK");
        //裂缝（水泥路面） 龟裂
        typeMap.put("22", "PIC_CRACK_RESULT_CRACKED");
        //板块碎裂
        typeMap.put("23", "PIC_CRACK_RESULT_BROKEN_BOARD");
        //红白杆倒伏
        typeMap.put("24", "PIC_RED_AND_WHITE_ROD_DISEASE_RESULT_DISEASE_FALL_DOWN");
        //护栏倾斜
        typeMap.put("25", "PIC_FENCE_DISEASE_RESULT_DISEASE_TILT");
        //红白杆倾斜
        typeMap.put("26", "PIC_RED_AND_WHITE_ROD_DISEASE_RESULT_DISEASE_TILT");
        //窨井盖缺失
        typeMap.put("27", "PIC_MANHOLE_COVER_DISLOCATION_RESULT_DISEASE_MISS");
        //窨井盖翘动
        typeMap.put("28", "PIC_MANHOLE_COVER_DISLOCATION_RESULT_DISEASE_WRAPING");
        //窨井盖高差
        typeMap.put("29", "PIC_MANHOLE_COVER_DISLOCATION_RESULT_DISEASE_CLIFF");
        //路名牌倒伏
        typeMap.put("30", "PIC_TRAFFIC_SIGN_DISEASE_RESULT_DISEASE_FALL_DOWN");
        //路名牌倾斜
        typeMap.put("31", "PIC_TRAFFIC_SIGN_DISEASE_RESULT_DISEASE_FALL_TILT");
        //隔离墩倾斜
        typeMap.put("33", "PIC_ISOLATION_PIER_DISEASE_RESULT_DISEASE_SKEWED");
        //侧石损坏
        typeMap.put("35", "PIC_CURBSTONE_DISEASE_RESULT_DISEASE_BROKEN");
        //废物箱倒伏
        typeMap.put("36", "PIC_DUSTBIN_DISEASE_RESULT_DISEASE_FALL_DOWN");
        //废物箱倾斜
        typeMap.put("37", "PIC_DUSTBIN_DISEASE_RESULT_DISEASE_TILT");
        //垃圾箱垃圾外溢
        typeMap.put("38", "PIC_DUSTBIN_DISEASE_RESULT_DISEASE_SPILLOVER");
        //路面垃圾杂物洒落
        typeMap.put("39", "PIC_GARBAGE_BAG_DISEASE_RESULT_DISEASE_ROAD_SPRINKLE");
        //汽修占道
        typeMap.put("41", "PIC_ROAD_OCCUPY_DISEASE_RESULT");
//        //跳车颠簸
//        typeMap.put("42", "");
        //多人聚集
        typeMap.put("43", "多人聚集");
        JsonNode[] jsonNodes = JsonUtils.StringConvertorObject(rows.toString(), JsonNode[].class);
        for (JsonNode jsonNode : jsonNodes) {
            String comId = jsonNode.get("comid").asText();
            if (StringUtils.isEmpty(comId)) {
                continue;
            }

            String hitId = jsonNode.get("sid").asText();
            if (StringUtils.isEmpty(hitId)) {
                continue;
            }

            String cox = jsonNode.get("cox").asText();
            String coy = jsonNode.get("coy").asText();
            double longitude = 0;
            double latitude = 0;
            try {
                longitude = Double.parseDouble(cox);
                latitude = Double.parseDouble(coy);
            } catch (Exception ignore) {
            }


            MultiValueMap<String, String> headers = new HttpHeaders();
            headers.set("Authorization", token);

            HttpEntity<Object> httpEntity1 = new HttpEntity<>(null, headers);
            ResponseEntity<JsonNode> hitNode = restTemplate.exchange("https://117.131.26.43:9999/prod-api/system/complainunfinishedhisdata/" + comId,
                    HttpMethod.GET, httpEntity1, JsonNode.class);
            JsonNode data = hitNode.getBody().get("data");
            String appealContent = data.get("appealContent").asText();
            int curposition = data.get("curposition").asInt();
            int curstatus = jsonNode.get("curstatus").asInt();
            String departid = data.get("departid").asText();
            String deviceid = data.get("deviceid").asText();
            String disType = data.get("disType").asText();
            String eventaddress = data.get("eventaddress").asText();
            String eventdescription = data.get("eventdescription").asText();
            String eventpictures = data.get("eventpictures").asText();
            String findtime = data.get("findtime").asText();
            String projectid = data.get("projectid").asText();
            String roadname = data.get("roadname").asText();
            String[] split = findtime.split(" ");
            String dayStr = split[0];
            String[] split1 = eventpictures.split("/");
            if (split1.length != 2) {
                log.error("eventpictures error,{}", eventpictures);
                continue;
            }
            String[] pic = split1[1].split("_");
            if (pic.length != 2) {
                log.error("eventpictures error,{}", eventpictures);
                continue;
            }

            String drawUrl = "http://yitu-aicar.oss-cn-shanghai.aliyuncs.com/disease138/" + deviceid + "/" +
                    dayStr.replaceAll("-", "") + "/" + pic[0] + ".jpg";

            Date date = MyDateUtil.strParseDate(findtime, "yyyy-MM-dd HH:mm:ss");
            Hit hit = new Hit();
            hit.setId(hitId);
            hit.setCreationTime(date.getTime() / 1000);
            hit.setHitTime(date.getTime() / 1000);
            hit.setFirstHitTime(date.getTime() / 1000);
            hit.setLastModificationTime(date.getTime() / 1000);
            HitAttrs attrs = new HitAttrs();
            attrs.setStatus(curstatusMap.get(curstatus + ""));
            attrs.setSceneImage(drawUrl);
            attrs.setCarId(deviceid);
            attrs.setFrameImageUrl(drawUrl);
            attrs.setConfirmation(Confirmation.builder().status(Confirmation.ConfirmationStatus.CORRECT).build());
            attrs.setHandleOfficeCode(departid);
            attrs.setRoadName(roadname);
            RoadInfo roadInfo = roadNameMap.get(roadname);

            String roadType;
            if (disType.equals("21") || disType.equals("20")) {
                roadType = "ROAD_TYPE_ASPHALT";
            } else if (disType.equals("22")) {
                roadType = "ROAD_TYPE_CEMENT";
            } else {
                roadType = "ROAD_TYPE_UNKNOWN";
            }
            if (Objects.nonNull(roadInfo)) {
                attrs.setRoadType(roadType);
                attrs.setHandleCompanyCode(roadInfo.getCompanyId());
                attrs.setHandleCompany(roadInfo.getCompanyName());
                hit.setRoadType(roadType);
            }

            attrs.setLocation(Lists.newArrayList(longitude, latitude));
            GpsLocation location = new GpsLocation();
            location.setLatitude(latitude);
            location.setLongitude(longitude);
            attrs.setGpsLocation(location);
            String s = typeMap.get(disType);
            if (StringUtils.isEmpty(s)) {
                continue;
            }
            DiseaseConfigInfo diseaseConfigInfo1 = diseaseConfig.getMap().get(s);
            if (Objects.isNull(diseaseConfigInfo1)) {
                continue;
            }

            hit.setType(s);
            hit.setScene(diseaseConfigInfo1.getScene());
            hit.setClassification(diseaseConfigInfo1.getClassification());
            attrs.setLimitHour(diseaseConfigInfo1.getLimitHour());
            attrs.setLoop(diseaseConfigInfo1.getLoop());

            hit.setAttrs(attrs);

            hit.setList(Lists.newArrayList(HistoryHit.fromHit(hit)));
            HitSubject subject = new HitSubject();
            subject.setBbox(Bbox.builder().h(0).w(0).x(0).y(0).build());
            subject.setRelBbox(RelBbox.builder().h(0.0).w(0.0).x(0.0).y(0.0).build());
            hit.setSubjects(Lists.newArrayList(subject));
            System.out.println(hit);
            Hit fetch = hitDao.fetch(hitId);
            if (Objects.isNull(fetch)) {
                hitDao.insert(hit);
            } else {
                hitDao.saveOrUpdate(hit);
            }
        }
        System.out.println(jsonNodes);
    }
}
